package com.yaoyong.yy_demo.module.chatroom.controller;

import com.yaoyong.yy_demo.module.chatroom.entity.WiselyMessage;
import com.yaoyong.yy_demo.module.chatroom.entity.WiselyResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

/**
 * @author 86188
 */
@Controller
public class WsController {

    /**
     * 需求:当一个浏览器发送一个消息到服务端时,其他浏览器也能接收到从服务端发送来的这个消息
     *
     * @param wiselyMessage
     * @return
     * @throws Exception
     */
    @MessageMapping("/welcome")
    @SendTo("/topic/getResponse")
    public WiselyResponse say(WiselyMessage wiselyMessage) throws Exception {
        Thread.sleep(3000);
        return new WiselyResponse("Welcome, " + wiselyMessage.getName() + "!");
    }

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 两个用户登录系统可以互发消息
     *
     * @param principal
     * @param msg
     */
    @MessageMapping("/chat")
    public void handleChat(Principal principal, String msg) {
        //此处是硬编码
        if (principal.getName().equals("yao")) {
            messagingTemplate.convertAndSendToUser("wisely", "/queue/notifications", principal.getName() + "-send: " + msg);
        } else {
            messagingTemplate.convertAndSendToUser("yao", "/queue/notifications", principal.getName() + "-send: " + msg);
        }
    }
}
